package com.zhangsun.expection;

import cn.hutool.log.StaticLog;
import com.zhangsun.base.bean.ResponseData;
import com.zhangsun.common.utils.ResponseUtil;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.stream.Collectors;

/**
 * 统一的异常处理
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 请求的 JSON 参数在请求体内的参数校验
     *
     * @param e 异常信息
     * @return 结果
     */
    @ExceptionHandler(BindException.class)
    @ResponseBody
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseData bindExceptionHandler(BindException e) {
        StaticLog.error(e);
        String errors = e.getAllErrors().stream().map(ObjectError::getDefaultMessage).collect(Collectors.joining("；"));
        return ResponseUtil.error(errors);
    }

    /**
     * url上的参数校验
     *
     * @param e 异常信息
     * @return 结果
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseData constraintViolationExceptionHandler(ConstraintViolationException e) {
        StaticLog.error(e);
        String errors = e.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining("；"));
        return ResponseUtil.error(errors);
    }

    /**
     * 业务异常的统一处理
     *
     * @param e 异常
     * @return 结果
     */
    @ExceptionHandler(value = BusinessException.class)
    @ResponseBody
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseData businessErrorHandler(BusinessException e) {
        StaticLog.error(e);
        return ResponseUtil.error(e.getMessage());
    }

    /**
     * 其他异常的统一处理
     *
     * @param e 异常
     * @return 结果
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseData defaultErrorHandler(Exception e) {
        StaticLog.error(e);
        return ResponseUtil.error("系统异常" + e.getMessage());
    }

}
